package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Commodity;
import com.owen.pojo.Fenlei;
import com.owen.server.CommodityServer;
import com.owen.server.FenleiServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/commodity")
public class CommodityContolle {

    @Autowired
    private CommodityServer commodityServer;

    @Autowired
    private FenleiServer fenleiServer;

    @ResponseBody
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public String findAll() {
        PageHelper.startPage(1, 10);
        List<Commodity> commodities = commodityServer.findAll();
        PageInfo<Commodity> commoditieInfo = new PageInfo<>(commodities);

        Map<String, Object> res = new HashMap<>();
        if (commodities != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", commoditieInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Commodity commodity, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Commodity> byCommodity = commodityServer.findByCommodity(commodity);
        // 填写数据
        List<Map<String, Object>> rows = byCommodity.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId().toString());
            maps.put("name", item.getName());
            maps.put("price", item.getPrice());
            maps.put("stock", item.getStock());
            maps.put("createTime", item.getCreateTime());
            return maps;
        }).collect(Collectors.toList());

        // 里面的标题
        int columns = Class.forName("com.owen.pojo.Commodity").getDeclaredFields().length;
        writer.merge(columns - 1, "商品信息");
        // 表头
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "商品名");
        writer.addHeaderAlias("price", "单价");
        writer.addHeaderAlias("stock", "库存");
        writer.addHeaderAlias("createTime", "创建时间");
        // 每一列间隔
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.write(rows, true);
        // 定义输出类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // 设置Header (下载时显示的名字)
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("商品信息-" + DateUtil.today() + ".xls", "utf-8"));

        // out用于输出字符流数据或者二进制的字节流数据都可以
        ServletOutputStream out = response.getOutputStream();
        // 刷新
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        // 关闭输出Servlet流
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "findBycommodity")
    public String findBycommodity(Long[] fenleiids, Commodity commodity, Integer xuanzhepage, Integer currentPage) {

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }
        PageHelper.startPage(current, xuanzhepage);
        List<Commodity> commoditys = commodityServer.findByCommodityByFenlei(commodity, fenleiids);
        PageInfo<Commodity> commodityInfo = new PageInfo<>(commoditys);

        Map<String, Object> res = new HashMap<>();
        if (commoditys != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", commodityInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public String findById(Integer id) {

        List<Fenlei> fenlei = fenleiServer.findFenlei();
        List<Fenlei> commodityFenlei = fenleiServer.findCommodityFenlei(id);
        Commodity commodity = commodityServer.findById(id);

        Map<String, Object> res = new HashMap<>();
        if (commodity != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", commodity);
            res.put("data2", fenlei);
            res.put("data3", commodityFenlei);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/ViewfindById", method = RequestMethod.GET)
    public String ViewfindById(Integer id) {
        List<Fenlei> commodityFenlei = fenleiServer.findCommodityFenlei(id);
        Commodity commodity = commodityServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        if (commodity != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", commodity);
            res.put("data2", commodityFenlei);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id) {
        Integer integer = commodityServer.deleteById(id);

        if (integer > 0) {
            Integer integer1 = commodityServer.deleteCommodityFenleiById(id);
        }

        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "查询成功");
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/updateById")
    public String updateById(Integer[] commodityFenlei, Commodity commodity) {

        Integer integer = commodityServer.updateById(commodity);

        if (integer > 0) {
            Integer integer1 = commodityServer.deleteCommodityFenleiById(Integer.valueOf(commodity.getId().toString()));
        }

        for (int i = 0; i < commodityFenlei.length; i++) {
            commodityServer.addCommodityFenlei(Integer.valueOf(commodity.getId().toString()), commodityFenlei[i]);
        }

        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "修改成功");
            res.put("data", commodity);
        } else {
            res.put("code", "201");
            res.put("msg", "修改失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer[] ids) {
        Map<String, Object> res = new HashMap<>();
        Integer count = commodityServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        } else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/addCommodity")
    public String addCommodity(Integer[] commodityFenlei, Commodity commodity) {

        Integer integer = commodityServer.addCommodityById(commodity);

        if (integer > 0) {
            Integer integer1 = commodityServer.deleteCommodityFenleiById(Integer.valueOf(commodity.getId().toString()));
        }

        System.out.println(Integer.valueOf(commodity.getId().toString()));

        for (int i = 0; i < commodityFenlei.length; i++) {
            commodityServer.addCommodityFenlei(Integer.valueOf(commodity.getId().toString()), commodityFenlei[i]);
        }

        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "添加成功");
            res.put("data", commodity);
        } else {
            res.put("code", "201");
            res.put("msg", "添加失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }



}
